package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.SkuPriceVo;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-20
 */
@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);

    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        // 封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        // 查询一个商品的所有sku
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getProductId, id)
                .select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        // 封装数据
        Map<String,Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        List<ProductSku> productSkuList = baseMapper.selectList(
                new LambdaQueryWrapper<ProductSku>()
                        .in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice)
        );
        return productSkuList.stream().map(item -> {
            SkuPriceVo skuPrice = new SkuPriceVo();
            skuPrice.setSkuId(item.getId());
            skuPrice.setSalePrice(item.getSalePrice());
            return skuPrice;
        }).collect(Collectors.toList());
    }
}
